package com.hao.tool.web.module.rbac.controller;

import com.hao.tool.common.constant.Commons;
import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.common.security.*;
import com.hao.tool.common.util.JsonKitUtil;
import com.hao.tool.web.module.rbac.entity.ManagerInfo;
import com.hao.tool.web.module.rbac.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 23:37
 */
@RestController
@RequestMapping("/rest/user")
public class UserRestController {


    @Autowired
    private ManagerService managerService;

    @PostMapping("/login")
    public LayResponse login(String userName, String passWord,
                             HttpServletResponse response) {
        ManagerInfo info = managerService.findByAccount(userName);
        if (info == null) {
            return LayResponse.builder().code(400).msg("用户不存在").build();
        } else {
            if (!info.getPassWord().equals(passWord)) {
                return LayResponse.builder().code(400).msg("密码不正确").build();
            }
        }

        info.setUpdateTime(LocalDateTime.now());


        JwtSubject tokenManager = JwtSubject.build()
                .setAccount(info.getUserName())
                .setId(info.getId())
                .setAccount(info.getAccount());
        String subject = JsonKitUtil.getString(tokenManager);
        JwtInfo jwtInfo = JwtInfo.build("jwt-user", subject, JwtConstant.DAY_1, null);
        // TODO: 2020-07-29 date 2 localDateTime
        String token = JwtUtil.buildToken(jwtInfo);

        info.setAccessToken(token);
        managerService.updateById(info);
        CookieUtil.saveCookie(response, JwtConstant.COOKIE_NAME, token);
        return LayResponse.builder().code(LayResponse.SUCCESS).data(info).build();
    }


    @GetMapping("")
    public LayResponse info(HttpServletRequest request) {
        String userName = (String) request.getAttribute(Commons.SUB_KEY);
        return LayResponse.builder().code(LayResponse.SUCCESS).build();
    }

    @PostMapping("/logout")
    public LayResponse logout(HttpServletResponse response, HttpServletRequest request) {
        CookieUtil.deleteCookie(response, JwtConstant.COOKIE_NAME);
        return LayResponse.builder().code(LayResponse.SUCCESS).build();
    }

}
